package com.zenith.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenith.edu.mapper.EduChapterMapper;
import com.zenith.edu.po.domain.EduChapter;
import com.zenith.edu.po.dto.EduChapterDTO;
import com.zenith.edu.po.vo.EduChapterVO;
import com.zenith.edu.service.EduChapterService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
    
    @Override
    public EduChapterVO createChapter(EduChapterDTO dto) {
        EduChapter chapter = new EduChapter();
        BeanUtils.copyProperties(dto, chapter);
        this.save(chapter);
        
        EduChapterVO vo = new EduChapterVO();
        BeanUtils.copyProperties(chapter, vo);
        return vo;
    }
    
    @Override
    public EduChapterVO getChapterById(Long id) {
        EduChapter chapter = this.getById(id);
        if (chapter == null) {
            return null;
        }
        
        EduChapterVO vo = new EduChapterVO();
        BeanUtils.copyProperties(chapter, vo);
        return vo;
    }
    
    @Override
    public EduChapterVO updateChapter(EduChapterDTO dto) {
        EduChapter chapter = new EduChapter();
        BeanUtils.copyProperties(dto, chapter);
        this.updateById(chapter);
        
        EduChapterVO vo = new EduChapterVO();
        BeanUtils.copyProperties(chapter, vo);
        return vo;
    }
    
    @Override
    public boolean deleteChapter(Long id) {
        return this.removeById(id);
    }
    
    @Override
    public List<EduChapterVO> getChapterList() {
        List<EduChapter> chapterList = this.list();
        return chapterList.stream().map(chapter -> {
            EduChapterVO vo = new EduChapterVO();
            BeanUtils.copyProperties(chapter, vo);
            return vo;
        }).collect(Collectors.toList());
    }
    
    @Override
    public List<EduChapterVO> getChaptersByCourseId(Long courseId) {
        LambdaQueryWrapper<EduChapter> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EduChapter::getCourseId, courseId);
        List<EduChapter> chapterList = this.list(queryWrapper);
        return chapterList.stream().map(chapter -> {
            EduChapterVO vo = new EduChapterVO();
            BeanUtils.copyProperties(chapter, vo);
            return vo;
        }).collect(Collectors.toList());
    }
}